#include "towerbase2.h"
#include <QPainter>
#include <QPixmap>
#include<QTimer>
#include"utility.h"
#include<QVector2D>
towerbase2::towerbase2(QPoint pos, window4 *game2,QPixmap Pic):Tower_pos(pos),_Pic(Pic)
{

  this->game2=game2;
     ms_fixedSize=QSize(Pic.width(),Pic.height());
    Attack_range=150;
    Attack_speed=100;
    Tower_damage=20;
    mrotationpixmap=0.0;
    _choose_enemy=NULL;
    _fireRate=new QTimer(this);
    connect(_fireRate,SIGNAL(timeout()),SLOT(shoot_bulluet()));

    fire_time = 1;

}
void towerbase2::draw(QPainter *painter)
{
    painter->save();
    painter->setPen(Qt::blue);

    painter->drawEllipse(Tower_pos, Attack_range, Attack_range);
    QPixmap sprite(":/22/button3.png");
    static const QPoint transpoint(-22,-22);

    painter->translate(Tower_pos);
    painter->drawPixmap(transpoint, _Pic);
    painter->restore();
}

void towerbase2::attack_enemy(){
    _fireRate->start(show_firerate());
}

int towerbase2::show_firerate(){
    return this->fire_time;
}

int towerbase2::show_damage(){
    return this->Tower_damage;
}
int towerbase2::show_firerange(){
    return this->Attack_range;
}

void towerbase2::choose_enemy(Enemy2 *enemy){
    _choose_enemy=enemy;
    attack_enemy();
    _choose_enemy->get_attacked(this);

}
void towerbase2::shoot_bulluet(){
    bullet2 *_bulluet=new bullet2(Tower_pos,_choose_enemy->pos(),show_damage(),_choose_enemy,game2,":/bullet1.png");
    _bulluet->move();
    game2->add_bulluet(_bulluet);
}

void towerbase2::lose_sight(){
    _choose_enemy->get_lostsight(this);
    if(_choose_enemy)
        _choose_enemy=NULL;
    _fireRate->stop();
    mrotationpixmap=0.0;
}

void towerbase2::check_enemy_range()
{
    if (_choose_enemy)
    {
        QVector2D normalized(_choose_enemy->pos() - Tower_pos);
        normalized.normalize();
        mrotationpixmap = qRadiansToDegrees(qAtan2(normalized.y(), normalized.x())) - 90;

        if (!if_collision(Tower_pos, show_firerange(), _choose_enemy->pos(), 1))
            lose_sight();
    }
    else
    {

        QList<Enemy2 *> enemyList =game2->enemy_list();
        foreach (Enemy2 *enemy2, enemyList)
        {
            if (if_collision(Tower_pos,show_firerange(), enemy2->pos(), 1))
            {
                choose_enemy(enemy2);
                break;
             }
        }
    }
}
void towerbase2::target_killed(){
    if(_choose_enemy)
        _choose_enemy=NULL;
    _fireRate->stop();
    mrotationpixmap=0.0;
}
